<template>
  <v-overlay persistent @update:modelValue="onUpdate">
    <div  class="create-overlay">
      <div class="create-room" v-loading="loading">
        <div class="create-room-title">
          创建房间
          <img
            src="@/static/img/battle/icon-close.png"
            class="cursor-pointer"
            @click="handleClose"
          />
        </div>

        <div class="create-room-main">
          <!-- header -->
          <div class="create-room-header flex-column flex-md-row align-center">
            <div
              class="d-flex justify-space-between justify-md-center align-center"
            >
              <!-- 价值 -->
              <div class="total-value">
                <div>
                  <img src="@/static/img/icon/coin.png" />
                  <span>{{ selectInfo.totalPrice }}</span>
                </div>

                <div>总价值</div>
              </div>

              <!-- 回合数 -->
              <div class="round-box">
                <div class="round">
                  <span>{{ selectInfo.boxCount }}</span>
                  回合
                </div>
              </div>
            </div>

            <!-- 人数 -->
            <div class="mode">
              <div class="mode-title subtitle">人数</div>

              <custom-tabs :options="modes" v-model="activeMode"></custom-tabs>
            </div>

            <!-- 模式 -->
            <div class="mode">
              <div class="mode-title subtitle">模式</div>

              <custom-tabs :options="modes2" v-model="activeMode2"></custom-tabs>
            </div>

            
          </div>

          <!-- box -->
          <div class="select-box">
            <div class="select-box-header">
              <div class="subtitle select-box-title">选择箱子</div>
              <custom-tabs
                :options="boxTypes"
                v-model="activeBoxType"
                @change="onTabChange"
              ></custom-tabs>
            </div>

            <!-- 可选列表 -->
            <div class="select-box-list">
              <box-item
                v-for="box in boxList"
                :key="box.id"
                :box="box"
                @click="handleSelectBox(box)"
              ></box-item>
            </div>

            <!-- 已选 -->
            <div class="d-flex justify-space-between align-center selected-row">
              <div class="subtitle mt-3">已选箱子</div>
              <div class="text-white selected-box-tip">
                已选择<span>{{ selectInfo.boxCount }}</span
                >个箱子
              </div>
            </div>

            <div class="selected-box-list battle-scrollbar">
              <box-item
                v-for="box in selectedBoxList"
                :box="box"
                :key="box.id"
                active
                toolbar
                @click="handleUnselectBox(box)"
              ></box-item>
            </div>
          </div>
        </div>

        <div class="d-flex" style="align-items: center;justify-content: center">
          <el-input
                  placeholder="如需密码请填写"
                  v-model="password"
                  clearable
                  size="medium"
                  style="width: 200px;margin-right: 20px"
          ></el-input>
          <v-btn
            color="#8E7EED"
            class="text-white create-button"
            @click="createRoom"
            >创建房间</v-btn
          >
        </div>
      </div>
    </div>
  </v-overlay>
</template>
<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  toRefs,
  computed,
  setTransitionHooks,
} from "vue";
import CustomTabs from "./Tabs.vue";
import BoxItem from "./BoxItem.vue";
import BoxService from "@/services/BoxService";
import BattleService from "@/services/BattleService";
import { processImageUrl } from "@/utils";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

export interface BoxType {
  id: number;
  name: string;
}

export interface Box {
  id: number;
  name: string;
  price: number;
  img: string;
  _count: number;
}

export default defineComponent({
  setup(props, { emit }) {
    const state = reactive({
      loading: false,
      boxTypes: [],
      boxList: [],
      selectedBoxList: [] as Box[],
      submitBoxList: [] as Box[],
      boxTypeId: -1,
      activeBoxType: 0,
      password:'',
      selectInfo: computed(() => {
        let totalPrice = 0;
        let boxCount = 0;

        state.selectedBoxList.forEach((box) => {
          const { price, _count } = box;
          totalPrice += price * _count;
          boxCount += _count;
        });

        return {
          totalPrice: totalPrice.toFixed(2),
          boxCount,
        };
      }),

      modes: [
        {
          name: "二人",
          value: 2,
        },
        {
          name: "三人",
          value: 3,
        },
        {
          name: "四人",
          value: 4,
        },
      ],
      activeMode: 0,
      modes2: [
        {
          name: "天命",
          value: false,
        }
      ],
      activeMode2: 0,
    });

    const router = useRouter();

    const getBoxTypes =async () => {
      try{
        state.loading = true;
        const { data } =  await BoxService.allType({
          type: 1,
        });
        state.boxTypes = data.data;
        return data.data;
      }finally{
        state.loading = false;
      }
    };

    const getBoxs = async () => {
      try{
      state.loading = true;
      const response = await    BoxService.list({
          type_id: state.boxTypeId,
          page: 1,
          page_size: 999,
          box_type: 1,
        });
          const { list, total } = response.data.data;
          state.boxList = list.map((item) => ({
            ...item,
            img: processImageUrl(item.img),
          }));

      }finally{
          state.loading = false;
      }
    };

    const createRoom = () => {
      if (!state.selectInfo.boxCount) {
        ElMessage.warning("还未选择箱子");
        return;
      }

      const { modes, activeMode, modes2, activeMode2, submitBoxList,password } = state;
      state.loading = true;

      BattleService.createRoom({
        num: modes[activeMode].value,
        is_reverse: modes2[activeMode2].value,
        box_ids: submitBoxList.map((box) => box.id),
        password:password
      })
        .then((res) => {
          ElMessage.success("创建房间成功");
          const roomId = res.data.data.room_id;
          emit("close");
          emit("created", roomId);
          router.push(`/battle/${roomId}`);
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const initData = async () => {
      try{
        const types = await getBoxTypes();
        if(types && types.length>0){
          state.boxTypeId = types[0].id;
         await getBoxs();
        }
      }finally{

      }
    };

    const reset = () => {
      state.boxTypeId = -1;
      state.boxList = [];
      state.selectedBoxList = [];
      state.submitBoxList = [];
      state.activeMode = 0;
      state.activeBoxType = 0;
      initData();
    };

    onMounted(() => {
      initData();
    });

    return {
      ...toRefs(state),

      async onTabChange(type: BoxType) {
        state.boxTypeId = type.id;
        await getBoxs();
      },

      handleSelectBox(box: Box) {
        const max = 10;

        if (state.selectInfo.boxCount === max) {
          ElMessage.warning(`最多只能选择${max}个箱子`);
          return;
        }

        const selectedBox = state.selectedBoxList.find(
          (item) => item.id === box.id
        );
        state.submitBoxList.push(box);

        if (selectedBox) {
          selectedBox._count++;
        } else {
          state.selectedBoxList.push({
            ...box,
            _count: 1,
          });
        }
      },

      handleUnselectBox(box: Box) {
        const selectedBox = state.selectedBoxList.find(
          (item) => item.id === box.id
        );

        if (selectedBox) {
          const { _count } = selectedBox;
          if (_count > 1) {
            selectedBox._count--;
          } else {
            state.selectedBoxList = state.selectedBoxList.filter(
              (item) => item.id !== box.id
            );
          }
        }

        const index = state.submitBoxList
          .slice()
          .reverse()
          .findIndex((item) => item.id === box.id);
        if (index > -1) {
          state.submitBoxList.splice(index, 1);
        }
      },

      handleClose() {
        emit("close");
        reset();
      },

      onUpdate(newValue: boolean) {
        if (newValue) return;
        reset();
      },
      createRoom,
    };
  },

  components: {
    CustomTabs,
    BoxItem,
  },
});
</script>

<style scope lang="scss">
.create-overlay{
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.create-room {
  width: 1200px;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: #1c192a;
  padding-bottom: 20px;

  > * {
    flex: none;
  }

  .create-room-main {
    padding: 0 36px 0 36px;
    flex: 1;
    overflow-x: hidden;
    overflow-y: auto;
    margin-bottom: 20px;
  }
}

.create-room-title {
  background: #28253b;
  font-size: 20px;
  line-height: 52px;
  color: rgba(255, 255, 255, 0.56);
  font-weight: 600;
  text-indent: 32px;
  position: relative;

  img {
    width: 18px;
    height: 18px;
    position: absolute;
    top: 50%;
    right: 32px;
    transform: translateY(-50%);
  }
}

.create-room-header {
  display: flex;
  margin-top: 10px;

  .total-value {
    div:first-child {
      font-size: 24px;
      color: #ffffff;
      margin-bottom: 2px;
      display: flex;
      align-items: center;

      img {
        width: 33px;
        margin-right: 7px;
      }
    }

    div:last-child {
      font-size: 16px;
      color: rgba(255, 255, 255, 0.4);
      text-align: right;
    }
  }

  .round-box {
    width: 152px;
    height: 132px;
    display: flex;
    justify-content: center;
    align-items: center;

    .round {
      background: rgba(40, 37, 59, 0.39);
      border: 4px solid #8e7eed;
      box-shadow: 0px 0px 24px rgba(142, 126, 237, 0.78);
      border-radius: 50%;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.7);
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80px;
      height: 80px;

      span {
        font-size: 24px;
        font-weight: bold;
        color: #fff;
        margin-right: 4px;
      }
    }
  }

  .mode {
    .mode-title {
      margin-bottom: 15px;
    }
  }
}

.select-box {
  .select-box-title {
    margin-bottom: 11px;
  }

  .select-box-list {
    display: flex;
    flex-wrap: wrap;
    max-height: 309px;
    overflow-y: auto;
    margin-top: 10px;

    > * {
      margin-right: 20px;
      margin-bottom: 11px;

      &:nth-child(7n + 7) {
        margin-right: 0;
      }
    }
  }

  .selected-box-list {
    display: flex;
    overflow-x: auto;
    margin-top: 10px;

    > * {
      margin-right: 16px;

      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.subtitle {
  color: #fff;
  font-size: 20px;
  font-weight: bold;
}

.selected-box-tip {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.5);
  display: flex;
  align-items: center;

  span {
    color: #8847ff;
    margin: 0 5px;
    font-size: 20px;
  }
}
</style>

<style scoped lang="scss">
@media screen and (max-width: 600px) {
  .create-room {
    max-width: 100vw;
  }

  .create-room-title {
    font-size: 16px;
    line-height: 40px;
    text-indent: 16px;

    img {
      width: 15px;
      height: 15px;
      right: 16px;
    }
  }

  .create-room-main {
    padding: 0 20px;
  }

  .create-room-header {
    margin-top: 20px;

    > div:first-child {
      width: 100%;
      margin-bottom: 12px;
    }

    .total-value {
      div:first-child {
        font-size: 14px;
        margin-bottom: 4px;

        img {
          width: 16px;
          margin-right: 4px;
        }
      }

      div:last-child {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.4);
      }
    }

    .round-box {
      width: 60px;
      height: 60px;

      .round {
        width: 100%;
        height: 100%;
        font-size: 12px;
        border-width: 1px;

        span {
          font-size: 16px;
        }
      }
    }

    .mode {
      display: flex;
      align-items: center;
      margin-right: auto;

      > *:first-child {
        margin-right: 8px;
      }

      .mode-title {
        margin-bottom: 0;
      }
    }
  }

  .select-box {
    .select-box-list {
      // margin-top: 16px;
      flex-wrap: nowrap;
      max-height: 142px;
      // height: 136px;

      > * {
        margin-right: 6px;
        margin-bottom: 0;
      }
    }

    .select-box-header {
      display: flex;
      margin-top: 16px;

      > *:first-child {
        margin-bottom: 0;
        margin-right: 8px;
        margin-top: 8px;
        flex: none;
      }
    }
  }

  .selected-box-tip {
    font-size: 12px;

    span {
      font-size: 12px;
      margin: 0 3px;
    }
  }

  .subtitle {
    font-size: 12px;
    font-weight: normal;
    margin-top: 0 !important;
  }

  .selected-row {
    margin-top: 10px;
  }

  .create-button {
  }
}
</style>
